package com.verysimple.flipcard
{

	import flash.utils.setTimeout;
	
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Button;
	import mx.events.FlexEvent;

	public class FlipCardContainer extends VBox
	{
		public static var BUTTON_TOP:String = "top";
		public static var BUTTON_BOTTOM:String = "bottom";
		public static var BUTTON_HIDDEN:String = "hidden";
		
		public var buttonTextFront:String = "Flip ››";
		public var buttonTextBack:String = "‹‹ Return";
		public var buttonPosition:String = FlipCardContainer.BUTTON_BOTTOM;
		public var flipButton:Button;
		public var flipCard:FlipCard;
		public var flipButtonContainer:HBox;
		
		public function FlipCardContainer()
		{
			this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
						
			this.flipButton = new Button();
			this.flipButton.styleName = "FlipCardButton";

			this.flipButtonContainer = new HBox;
			this.flipButtonContainer.styleName = "FlipCardButtonContainer";
			this.flipButtonContainer.percentWidth = 100;
			this.flipButtonContainer.addChild(this.flipButton);
			
			super();
			
			this.addChild(this.flipButtonContainer);
			
		}
		
		/**
		 * Fires on FlexEvent.CREATION_COMPLETE
		 */
		private function onCreationComplete(event:FlexEvent):void
		{
			if (this.styleName == null) this.styleName = "FlipCardContainer";
			
			this.flipCard = this.getChildAt(1) as FlipCard;
			
			if (buttonPosition == FlipCardContainer.BUTTON_BOTTOM)
				this.swapChildren(flipCard,flipButtonContainer);
			
			if (this.flipCard == null)
			{
				throw new Error("The first sub-component in a FlipCardContainer must be a FlipCard");
			}
			
			this.flipButton.addEventListener(FlexEvent.BUTTON_DOWN,toggle);
			
			this.flipButton.label = this.buttonTextFront;
			this.flipButtonContainer.visible = (buttonPosition != FlipCardContainer.BUTTON_HIDDEN);

		}
		
		/**
		 * 
		 */
		public function toggle(event:FlexEvent):void
		{
			this.flipButton.enabled = false;
			this.flipCard.toggle(event);
			flash.utils.setTimeout(toggleButtonText,250 + (this.flipCard.flipSpeed*2) );
		}
		
		private function toggleButtonText():void
		{
			this.flipButton.label = (this.flipButton.label == this.buttonTextFront) ? this.buttonTextBack : this.buttonTextFront;
			this.flipButton.enabled = true;
		}

	}
}